import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from utils.json import JSONHandler
from dao.index import LoginSchema
from components.messageBox import CustomMessageBox

class RoundedResetUI(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.setupStyles()
        self.drag_pos = QPoint()
        self.json = JSONHandler("./config/cache.json")

    def initUI(self):
        # 窗口设置
        self.setWindowFlag(Qt.FramelessWindowHint)
        self.setFixedSize(380, 480)
        self.setAttribute(Qt.WA_TranslucentBackground)
        # 设置窗口标志
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)

        # 隐藏标题栏
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowTitleHint)

        # 主布局
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(50, 60, 50, 60)
        main_layout.setSpacing(30)

        # 输入字段
        self.id_input = self.create_input("请输入学号/教师工号")
        self.name_input = self.create_input("请输入姓名")
        self.pwd_input = self.create_input("请输入新密码", password=True)
        self.confirm_pwd = self.create_input("确认新密码", password=True)

        # 操作按钮
        self.action_btn = QPushButton("下一步")
        self.action_btn.setCursor(Qt.PointingHandCursor)

        # 关闭按钮（修改后）
        self.close_btn = QPushButton("×", self)
        self.close_btn.setObjectName("closeButton")
        self.close_btn.setFixedSize(30, 30)
        self.close_btn.move(self.width() - 40, 10)  # 调整到更靠近右上角
        self.close_btn.clicked.connect(self.close)
        self.close_btn.setCursor(Qt.PointingHandCursor)

        # 初始隐藏字段
        self.name_input.hide()
        self.pwd_input.hide()
        self.confirm_pwd.hide()

        # 构建布局
        main_layout.addStretch(1)
        main_layout.addWidget(self.id_input)
        main_layout.addWidget(self.name_input)
        main_layout.addWidget(self.pwd_input)
        main_layout.addWidget(self.confirm_pwd)
        main_layout.addWidget(self.action_btn)
        main_layout.addStretch(1)

        self.setLayout(main_layout)

        # 信号连接
        self.action_btn.clicked.connect(self.process_steps)

    def create_input(self, placeholder, password=False):
        input_field = QLineEdit()
        input_field.setPlaceholderText(placeholder)
        input_field.setMinimumHeight(45)
        if password:
            input_field.setEchoMode(QLineEdit.Password)
        return input_field

    def setupStyles(self):
        style = """
        QLineEdit {
            background: rgba(255, 255, 255, 0.85);
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 8px;
            padding: 12px 20px;
            font-size: 15px;
            color: #444;
        }
        QLineEdit:focus {
            border-color: rgba(147, 112, 219, 0.8);
            background: rgba(255, 255, 255, 0.95);
        }
        QPushButton {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                stop:0 rgba(123, 104, 238, 0.9), 
                stop:1 rgba(147, 112, 219, 0.9));
            border: none;
            border-radius: 8px;
            color: white;
            padding: 14px 28px;
            font-size: 15px;
            font-weight: 500;
            min-width: 120px;
        }
        QPushButton:hover {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                stop:0 rgba(106, 90, 205, 0.9), 
                stop:1 rgba(131, 111, 255, 0.9));
        }
        QPushButton#closeButton {
            border: none;
            color: rgba(0, 0, 0, 0.6);
            font-size: 24px;
            background: transparent;
            border-radius: 15px;
            min-width: 30px;
            max-width: 30px;
            min-height: 30px;
            max-height: 30px;
            padding: 0;
        }
        QPushButton#closeButton:hover {
            background: #FF0000;
            color: white;
        }
        QPushButton#closeButton:pressed {
            background: #FF0000;
            color: white;
        }
        """
        self.setStyleSheet(style)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        
        path = QPainterPath()
        path.addRoundedRect(QRectF(self.rect()), 8, 8)
        
        gradient = QLinearGradient(0, 0, self.width(), self.height())
        gradient.setColorAt(0, QColor(135, 206, 250))
        gradient.setColorAt(1, QColor(221, 160, 221))
        painter.fillPath(path, gradient)

    def process_steps(self):
        if self.id_input.isVisible():
            if not self.id_input.text().strip():
                self.show_error("请输入学号/工号")
                return
            self.id_input.hide()
            self.name_input.show()
            self.action_btn.setText("继续")
        elif self.name_input.isVisible():
            if not self.name_input.text().strip():
                self.show_error("请输入姓名")
                return
            if not self.get_info(self.id_input.text()):
                self.show_error("学号/工号或姓名错误")
                return
            self.name_input.hide()
            self.pwd_input.show()
            self.confirm_pwd.show()
            self.action_btn.setText("确认更改")
        else:
            if self.pwd_input.text() != self.confirm_pwd.text():
                self.show_error("两次输入的密码不一致")
                return
            if len(self.pwd_input.text()) < 6:
                self.show_error("密码至少需要6位")
                return
            self.devise(self.id_input.text())


    def get_info(self, user_id):
        user = LoginSchema().get_student(user_id) if not self.json.read()['is_teacher'] else LoginSchema().get_teacher(user_id)
        print(user)
        if not user:
            return False
        if user['name'] == self.name_input.text():
            return True
        return False

    def devise(self, user_id):
        if not self.json.read()['is_teacher']:
            LoginSchema().update_student(user_id, {'password': self.pwd_input.text()})
        else:
            LoginSchema().update_teacher(user_id, {'password': self.pwd_input.text()})
        self.show_success("密码已重置，请使用新密码登录")
        # 关闭当前窗口
        self.close()

    def show_success(self, message):
        msg_box = CustomMessageBox(self)
        msg_box.show_success(message)

    def show_error(self, message):
        msg_box = CustomMessageBox(self)
        msg_box.show_error(message)

    def mousePressEvent(self, event):
        self.drag_pos = event.globalPos()
        
    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            self.move(self.pos() + event.globalPos() - self.drag_pos)
            self.drag_pos = event.globalPos()
            event.accept()